<template>
  <div class="event-detail">
    <!-- 导航栏 -->
    <van-nav-bar
      title="活动详情"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right v-if="role === 'organizer'">
        <van-icon name="edit" class="edit-icon" @click="goToEditPage" />
      </template>
    </van-nav-bar>

    <!-- 活动信息 -->
    <div class="content">
      <!-- 活动名称 -->
      <h1 class="event-name">{{ event.name }}</h1>

      <!-- 活动图片 -->
      <div v-if="parsedPics.length > 0">
        <van-swipe class="event-pics" :autoplay="3000">
          <van-swipe-item
            v-for="(pic, index) in parsedPics"
            :key="index"
            @click="previewImage(index)"
          >
            <img :src="pic" alt="活动图片" />
          </van-swipe-item>
        </van-swipe>
      </div>

      <!-- 活动类型和地点 -->
      <div class="info">
        <div class="info-item">
          <van-icon name="location-o" class="info-icon" />
          <span class="label">活动位置：</span>
          <span class="value">{{ event.location }}</span>
        </div>
        <div class="info-item">
          <van-icon name="calendar-o" class="info-icon" />
          <span class="label">活动时间：</span>
          <span class="value">{{ event.startTime }} ~ {{ event.endTime }}</span>
        </div>
        <p>
          <span class="label">活动剩余人数：</span>
          <span class="value">{{ event.remaining }}/{{ event.number }}</span>
        </p>
        <p>
          <span class="label">时长：</span>
          <span class="value">{{ event.hours }} 小时</span>
        </p>
        <p>
          <span class="label">描述：</span>
          <span class="value">{{ event.description }}</span>
        </p>
      </div>

      <!-- 组织信息 -->
      <div class="organizer" v-if="role === 'user'">
        <h2>活动举办组织</h2>
        <div class="organizer-info" @click="goToOrganizerDetail">
          <img :src="event.organizerPic" alt="组织头像" class="organizer-pic" />
          <p>{{ event.organizerName }}</p>
        </div>
      </div>

      <!-- 动态状态按钮或提示 -->
      <div class="action-area" v-if="role === 'user'">
        <van-button
          v-if="status === 'not_registered'"
          type="primary"
          @click="handleRegister"
          class="full-width-button"
        >
          去报名
        </van-button>
        <p v-else-if="status === 'registered_pending_review'">报名审核中</p>
        <p v-else-if="status === 'reviewed_not_attended'">请等待活动结束</p>
        <van-button
          v-if="status === 'registered_pending_review'"
          type="danger"
          @click="handleCancelRegistration"
          class="full-width-button"
        >
          取消报名
        </van-button>
        <van-button
          v-else-if="status === 'attended_not_scored'"
          type="primary"
          @click="handleScore"
          class="full-width-button"
        >
          去打分
        </van-button>
        <p v-else-if="status === 'attended_scored'">感谢您的参与</p>
        <p v-else-if="status === 'event_ended_not_registered'">活动已结束</p>
        <p v-else-if="status === 'registration_full'">报名已满</p>
      </div>
    </div>

    <!-- 报名用户信息 -->
    <div v-if="role === 'organizer'" class="registered-users">
      <h2>已报名用户</h2>
      <van-search
        v-model="searchQuery"
        placeholder="搜索用户"
        @input="handleSearch"
      />
      <div class="user-list">
        <div
          v-for="user in visibleUsers"
          :key="user.id"
          class="user-card"
          @click="goToUserDetail(user.id)"
        >
          <img :src="user.pic" alt="用户头像" class="user-avatar" />
          <p class="user-name">{{ user.name }}</p>
        </div>
      </div>
      <van-button
        v-if="filteredUsers.length > 4"
        type="primary"
        size="small"
        @click="toggleExpand"
        class="toggle-button"
      >
        {{ expanded ? "收起" : "展开" }}
      </van-button>
    </div>

    <!-- 动态状态按钮或提示 -->
    <div class="action-area" v-if="role === 'organizer'">
      <van-button
        v-if="status === 'not_started'"
        type="primary"
        @click="goToReviewPage"
        class="full-width-button"
      >
        报名审核
      </van-button>
      <p v-else-if="status === 'in_progress'">活动当前进行中...</p>
      <van-button
        v-else-if="status === 'ended_not_feedback'"
        type="primary"
        @click="goToFeedbackPage"
        class="full-width-button"
      >
        填写参与情况
      </van-button>
      <p v-else-if="status === 'ended_with_feedback'">活动已结束</p>
    </div>
  </div>
</template>

<script>
import activityApi from "@/api/activity.js";
import userApi from "@/api/userProfile.js";
import organizerApi from "@/api/organizerProfile.js";
import { Dialog, Toast, ImagePreview } from "vant"; // 引入 ImagePreview 组件

export default {
  data() {
    return {
      event: {}, // 用于存储活动详情
      eventId: "",
      status: "",
      role: "",
      registeredUsers: [], // 报名用户列表
      searchQuery: "", // 搜索框输入
      expanded: false, // 展开/收起状态
    };
  },
  mounted() {
    this.eventId = this.$route.query.id;
    this.role = this.$route.query.role; // 从路由中获取角色信息
    this.fetchEventDetail();
    if (this.role === "user") {
      this.getUserEventState();
    } else {
      this.getOrganizerEventState();
      organizerApi.getEventRegisterUser(this.eventId).then((res) => {
        this.registeredUsers = res;
      });
    }
  },
  computed: {
    parsedPics() {
      // 解析活动图片
      try {
        return JSON.parse(this.event.pics || "[]");
      } catch (e) {
        console.error("Error parsing pics:", e);
        return [];
      }
    },
    filteredUsers() {
      // 根据搜索框过滤用户
      return this.registeredUsers.filter((user) =>
        user.name.includes(this.searchQuery)
      );
    },
    visibleUsers() {
      // 控制显示的用户数量
      return this.expanded
        ? this.filteredUsers
        : this.filteredUsers.slice(0, 4);
    },
  },
  methods: {
    handleCancelRegistration() {
      Dialog.confirm({
        title: "取消报名",
        message: "您确定要取消报名此活动吗？",
      })
        .then(() => {
          // 用户点击确认后执行取消报名逻辑
          userApi.cancelRegistration(this.eventId).then(() => {
            Toast.success("已取消报名");
            this.status = "not_registered"; // 更新状态
          });
        })
        .catch(() => {
          // 用户点击取消
          Toast("已取消操作");
        });
    },
    goToReviewPage() {
      this.$router.push(`/review?id=${this.eventId}`);
    },
    // 跳转至填写参与情况页面
    goToFeedbackPage() {
      this.$router.push(`/feedback?id=${this.eventId}`);
    },
    handleSearch(query) {
      this.searchQuery = query; // 更新搜索框内容
    },
    toggleExpand() {
      this.expanded = !this.expanded; // 切换展开/收起状态
    },
    goToUserDetail(userId) {
      this.$router.push(`/userDetail?id=${userId}`); // 跳转到用户详情页
    },
    goToEditPage() {
      this.$router.push(`/pushEvents?id=${this.eventId}`);
    },
    // 点击报名按钮的处理逻辑
    handleRegister(activityId) {
      console.log("报名活动", activityId);
      // 调用报名接口
    },
    // 点击打分按钮的处理逻辑
    handleScore(activityId) {
      console.log("为活动打分", activityId);
      // 跳转到打分页面
      this.$router.push(`/score/${activityId}`);
    },
    fetchEventDetail() {
      activityApi.getEventDetail(this.eventId).then((res) => {
        console.log(res);
        this.event = res;
      });
    },
    getUserEventState() {
      activityApi.getEventStatus(this.eventId).then((res) => {
        this.status = res;
      });
    },
    getOrganizerEventState() {
      activityApi.getEventStatusOrganizer(this.eventId).then((res) => {
        console.log(res);
        this.status = res;
      });
    },
    goBack() {
      // 返回上一个页面
      this.$router.go(-1);
    },
    goToOrganizerDetail() {
      if (this.event.authId) {
        // 跳转到组织详情页，传递组织ID
        this.$router.push(`/organizerDetail?id=${this.event.authId}`);
      } else {
        // 组织ID不存在的情况
        this.$toast.fail("无法获取组织信息");
      }
    },
    // 图片预览功能
    previewImage(index) {
      ImagePreview({
        images: this.parsedPics, // 图片数组
        startPosition: index, // 当前点击的图片索引
        closeable: true, // 显示关闭按钮
        onClose() {
          console.log("图片预览关闭");
        },
      });
    },
    // 点击报名
    handleRegister() {
      Dialog.confirm({
        title: "确认报名",
        message: "您确定要报名此活动吗？",
      })
        .then(() => {
          // 用户点击确认后执行报名逻辑
          userApi.registerEvent(this.eventId).then(() => {
            Toast.success("报名成功！");
            this.status = "registered_pending_review";
          });
        })
        .catch(() => {
          // 用户点击取消
          Toast("已取消报名");
        });
    },
    // 点击打分
    handleScore() {
      this.$router.push(`/userScore/?id=${this.eventId}`);
    },
  },
};
</script>

<style scoped>
/* 动态状态提示文字颜色 */
.action-area p {
  font-size: 2vh;
  color: #808080; /* 灰色 */
  margin: 1vh 0;
}
.van-nav-bar ::v-deep .van-nav-bar__text,
.van-nav-bar ::v-deep .van-nav-bar__title {
  color: white !important;
}

.van-nav-bar ::v-deep .van-nav-bar__arrow {
  color: white !important;
}
/* 全局样式 */
.event-detail {
  font-family: Arial, sans-serif;
  height: 100vh;
  padding-bottom: 3vh;
}

.van-nav-bar {
  background-color: #007aff;
  color: white;
  height: 7vh;
  line-height: 8vh;
}

.van-nav-bar .edit-icon {
  font-size: 3vh;
  color: white;
}

/* 内容区 */
.content {
  padding: 0.5vh 1vh;
}

/* 活动名称 */
.event-name {
  font-size: 4vh;
  font-weight: bold;
  text-align: center;
  margin: 0 0 2vh;
}

/* 图片轮播 */
.event-pics {
  width: 100%;
  height: 35vh;
  margin-bottom: 2vh;
}
.event-pics img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 1vh;
}

/* 活动信息 */
.info {
  font-size: 2vh;
  color: #808080; /* 灰色 */
  margin-bottom: 4vh;
}
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 2vh;
}
.info-text {
  margin-left: 0.5vh;
  font-size: 2vh;
}
.info-icon {
  font-size: 2.5vh;
  color: #007aff;
}

.label {
  color: black;
}
.value {
  color: gray;
}

/* 组织信息 */
.organizer {
  font-size: 2vh;
  line-height: 3vh;
}
.organizer-info {
  display: flex;
  align-items: center;
  margin-top: 1vh;
}
.organizer-pic {
  width: 8vh;
  height: 8vh;
  border-radius: 50%;
  margin-right: 2vh;
}

/* 动态按钮区域 */
.action-area {
  margin-top: 4vh;
  text-align: center;
}

/* 全屏按钮样式 */
.full-width-button {
  width: 80%;
  max-width: 300px;
  margin: 1vh auto;
  background-color: #007aff; /* 与导航栏颜色一致 */
}

/* 已报名用户样式 */
.registered-users {
  margin-top: -3vh;
}

.user-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1vh;
}

.user-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1vh;
  background: #f7f7f7;
  border-radius: 0.5vh;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 增加阴影效果 */
  cursor: pointer;
  transition: transform 0.2s ease; /* 增加平滑过渡效果 */
}

.user-card:hover {
  transform: scale(1.05); /* 鼠标悬浮时放大 */
}

.user-avatar {
  width: 6vh;
  height: 6vh;
  border-radius: 50%;
}

.user-name {
  font-size: 2vh;
  color: #333;
}

.toggle-button {
  background-color: #007aff;
  margin-top: 1vh;
}

</style>
